package com.fare.taluo.core.domain.crawl.impl;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Blob;

import org.hibernate.Hibernate;
import org.hibernate.engine.jdbc.LobCreator;
import org.springframework.stereotype.Repository;

import com.dayatang.hibernate.EntityRepositoryHibernate;
import com.fare.taluo.core.domain.crawl.AdapterUploadedEntity;
import com.fare.taluo.core.domain.crawl.AdapterUploadedEntityRepository;
/*
 * 执行保存
*/
@Repository
public class AdapterUploadedEntityRepositoryImpl extends EntityRepositoryHibernate implements
		AdapterUploadedEntityRepository {

	@Override
	public Long SaveAdapterUploadedEntity(AdapterUploadedEntity aue) {
		// TODO Auto-generated method stub
		try {
			this.save(aue);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		return this.save(aue).getId();
	}
	public void removeS(AdapterUploadedEntity entity ){
		super.remove(entity);
	}
	@Override
	public AdapterUploadedEntity getById(Long id) throws Exception {
		return super.get(AdapterUploadedEntity.class, id);
	}
	@Override
	public AdapterUploadedEntity SaveAdapterUploadedEntity(AdapterUploadedEntity entity, File file)
			throws Exception {
		entity.setAdapterData(Hibernate.getLobCreator(getSession()).createBlob(this.fileToByte(file)));
		return this.save(entity);
	}
	
	@SuppressWarnings("unused")
	private Blob fileToBlob(File file) throws Exception{
		InputStream  is=null;;  
		Blob b = null;
		try {
			is=new FileInputStream(file);
			b=Hibernate.getLobCreator(getSession()).createBlob(is, is.available());
			return b;
		} finally{
			if(is!=null){
				is.close();
				is=null;
			}
		}
		
	}
	
	private byte[] fileToByte(File file) throws Exception {
			byte[] result=null;
			FileInputStream fis = null;  
	        ByteArrayOutputStream ops = null;  
	        byte[] temp = new byte[2048];  
	        try {
				fis = new FileInputStream(file);  
				ops = new ByteArrayOutputStream();  
				int n;  
				while ((n = fis.read(temp)) != -1) {  
				    ops.write(temp, 0, n);  
				}  
				result=ops.toByteArray();
				return result;
			} finally{
				temp=null;
				if(ops!=null){
					ops.close();
				}
				if(fis!=null){
					fis.close();
				}
				ops=null;fis=null;
			} 
	}
	
}
